<template>
  <a-table
    bordered
    :columns="columns"
    :data-source="dataset"
    :pagination="false"
    :scroll="{ x: minLength + 15, y: isUploading ? 400 : height - 70 }"
  >
    <template v-for="col in columns" :slot="`${col.key}Row`" slot-scope="text">
      <div :key="`${col.key}Row`">
        <a-tooltip>
          <template slot="title">
            {{ text }}
          </template>
          <span class="text-ellipsis">{{ text }}</span>
        </a-tooltip>
      </div>
    </template>
    <!-- <template v-for="col in columns" :slot="`${col.key}Title`"> -->
    <template v-for="(col, index) in columns" :slot="`${col.key}Title`">
      <div :key="`${col.key}Title`">
        <!-- 列标题 -->
        <a-tooltip>
          <template slot="title">
            {{ col.key }}
          </template>
          <span
            class="table-title"
            :style="{ 'max-width': colLength - 132 + 'px' }"
            >{{ col.key }}</span
          >
        </a-tooltip>

        <!-- 语义选择 -->
        <!-- <a-select
          v-if="showSelect"
          v-model="col.type"
          default-value="varchar"
          class="type-select"
          size="small"
          @change="(value) => handleChange(index, value)"
        >
          <a-select-option class="preview-table-select-option" value="varchar"
            >字符串</a-select-option
          >
            <a-select-option class="preview-table-select-option" value="varchar"
              >字符串</a-select-option
            >
            <a-select-option class="preview-table-select-option" value="date"
              >日期</a-select-option
            >
            <a-select-option class="preview-table-select-option" value="int"
              >整数</a-select-option
            >
            <a-select-option class="preview-table-select-option" value="decimal"
              >小数</a-select-option
            >
            <a-select-option class="preview-table-select-option" value="text"
              >文本</a-select-option
            >
          </a-select>
          <span v-else class="col-type"
            >({{ transformColumnType(col.type) }})</span
          >
          <a-select-option class="preview-table-select-option" value="int"
            >整数</a-select-option
          >
          <a-select-option class="preview-table-select-option" value="decimal"
            >小数</a-select-option
          >
          <a-select-option class="preview-table-select-option" value="text"
            >文本</a-select-option
          >
        </a-select>
        <span v-else class="col-type"
          >({{ transformColumnType(col.type) }})</span
        > -->
        <!-- 语义 21 01 28 -->
        <a-dropdown
          v-if="showSemantic && selectedImportType !== 'graph'"
          :trigger="['click']"
          :overlay-style="{ width: '120px' }"
          @visibleChange="(visible) => columnMenuClick(index, visible)"
        >
          <span class="column-type-icon-trigger">
            <a-icon-font
              :type="
                columnTypeIcon[col.type]
                  ? columnTypeIcon[col.type]
                  : 'iconshujuleixing-zifu'
              "
            />
            |
            {{
              col.semantic
                ? semanticMapping[col.semantic]
                  ? semanticMapping[col.semantic]
                  : col.semantic
                : '无'
            }}
            <a-icon
              :class="{ arrow: true }"
              type="caret-down"
              :style="{
                transform: menuIsVisible[index]
                  ? 'rotate(0deg)'
                  : 'rotate(180deg)',
              }"
            />
          </span>
          <a-menu
            slot="overlay"
            selectable
            :selected-keys="[col.type, col.semantic ? col.semantic : 'null']"
          >
            <!-- 数据库导入不显示 -->
            <template v-if="dataType !== 'database'">
              <a-menu-item disabled class="menu-group-title"
                >数据类型：</a-menu-item
              >
              <a-menu-item
                v-for="item in displayMenuItem"
                :key="item.value"
                @click="handleChange(index, item.value)"
              >
                <span
                  class="column-type-icon"
                  style="color: #5d637e !important;"
                >
                  <a-icon-font
                    :type="columnTypeIcon[item.value]"
                    fill="#5d637e"
                  />
                </span>
                {{ item.text }}
              </a-menu-item>
              <a-menu-divider />
            </template>
            <a-menu-item disabled class="menu-group-title">语义：</a-menu-item>
            <template v-for="semanticGroup in semanticType">
              <a-sub-menu
                v-if="semanticGroup.haveSub"
                :key="semanticGroup.name"
              >
                <span slot="title">
                  <span class="column-type-icon" style="margin-right: 6px;">
                    <a-icon-font :type="semanticGroup.icon" fill="#5d637e" />
                  </span>
                  <span>{{ semanticGroup.text }}</span>
                </span>
                <!-- 各语义分类下的语义 -->
                <a-menu-item
                  v-for="semantic in semanticGroup.detail"
                  :key="semantic.value"
                  @click="changeSemantic(index, semantic.value, col.key)"
                >
                  {{ semantic.chineseName }}
                </a-menu-item>
              </a-sub-menu>
              <a-menu-item
                v-else
                :key="semanticGroup.name"
                @click="changeSemantic(index, semanticGroup.name, col.key)"
              >
                {{ semanticGroup.text }}
              </a-menu-item>
            </template>
          </a-menu>
        </a-dropdown>
        <span v-else class="col-type" :title="semanticMapping[col.semantic]">
          ({{ semanticMapping[col.semantic] }})
        </span>

        <!-- 传入的更改 -->
        <!-- 语义 21 01 28 -->
        <!-- <template v-if="enableSemantic">
          <a-dropdown
            v-if="showSemantic"
            :trigger="['click']"
            :overlay-style="{ width: '120px' }"
          >
            <a-icon type="more" title="语义" style="cursor: pointer;" />
            <a-menu
              slot="overlay"
              selectable
              :selected-keys="
                col.semantic
                  ? [col.semantic]
                  : col.semanticSorted && [col.semanticSorted[0]]
              "
              :open-keys="['semantic']"
            >
              <a-sub-menu key="semantic" title="语义转换">
                <a-menu-item
                  v-for="item in col.semanticSorted"
                  :key="item"
                  @click="changeSemantic(index, item, col.key)"
                  >{{ semanticMapping[item] }}
                </a-menu-item>
              </a-sub-menu>
            </a-menu>
          </a-dropdown>
          <span
            v-else
            class="col-type"
            :title="semanticMapping[col.semantic]"
            >{{
              semanticMapping[col.semantic]
                ? `(${semanticMapping[col.semantic]})`
                : ''
            }}</span
          >
        </template> -->
      </div>
    </template>
  </a-table>
</template>

<script lang="ts">
/**
 * preview of single dataset
 * @author Huihua Lu
 */
import { Component, Vue, Prop, Emit, Watch } from 'vue-property-decorator'
import DataStore from '@/store/modules/data'
// import 数据预览表头 修改数据类型和语义的 menu 及其 icon 统一引入， 与 pipeline transform 保持一致
import {
  columnTypeIcon,
  columnSemanticClassificationIcon,
} from '@/components/studio/data/node-edit-panel/column-type-semantic-icon'
import {
  columnTypeMenu,
  columnSemanticMenu,
  semanticMapping,
} from '@/components/studio/data/node-edit-panel/column-type-semantic'
import { ISemantic } from '@/components/studio/data/node-edit-panel/interface'

@Component
export default class DatasetPreviewTable extends Vue {
  @Prop() head!: Array<any>
  @Prop() data!: Array<any>
  @Prop() dataType!: string
  @Prop({ default: true }) enableColType!: boolean // 显示类型相关操作
  @Prop({ default: true }) enableSemantic!: boolean // 显示语义相关操作
  @Prop({ default: 700 }) height!: number // 表格高度

  // 用于table列数的自适应
  private minLength = document.body.clientWidth - 285
  private colLength = 220

  // ---------- 语义推断 start
  public semanticMapping = semanticMapping // 语义 - 中文
  public semanticType: ISemantic[] = columnSemanticMenu // 语义 menu
  private columnTypeIcon = columnTypeIcon // 统一数据类型 icon
  private columnSemanticClassificationIcon = columnSemanticClassificationIcon // 统一语义 icon
  private menuItem = columnTypeMenu // 统一数据类型 menu
  public menuIsVisible: Array<boolean> = []

  @Emit('change-semantic')
  public changeSemantic(index: number, semantic: any, colName: string) {
    return { index, semantic, colName }
  }

  //  ---------- 语义推断 end

  @Watch('columns', { immediate: true })
  private onColumnsChange(newValue: any) {
    this.menuIsVisible = []
    for (let i = 0; i < newValue.length; i += 1) {
      this.menuIsVisible.push(true)
    }
  }

  public get columns() {
    if (DataStore.isSqlSearch) {
      this.minLength = document.body.clientWidth / 2 - 200
    } else {
      this.minLength = document.body.clientWidth - 330
    }
    const result: Array<any> = []
    if (this.head) {
      const count = Math.floor(this.minLength / this.colLength)
      this.head.forEach((item: any) => {
        if (this.head.length <= count) {
          // if (index === this.head.length - 1)
          result.push({
            dataIndex: item.name,
            key: item.name,
            type: item.type,
            slots: { title: `${item.name}Title` },
            width: this.minLength / this.head.length,
            // fixed: 'right',
            ellipsis: true,
            scopedSlots: { customRender: `${item.name}Row` },
            recommendSemantic: item.recommendSemantic,
            semantic: item.semantic,
          })
        } else {
          result.push({
            dataIndex: item.name,
            key: item.name,
            type: item.type,
            slots: { title: `${item.name}Title` },
            width: this.colLength,
            ellipsis: true,
            scopedSlots: { customRender: `${item.name}Row` },
            recommendSemantic: item.recommendSemantic,
            semantic: item.semantic,
          })
        }
      })
    }
    return result
  }

  public get dataset() {
    const result: Array<any> = []
    if (this.data) {
      this.data.forEach((item: any, index: number) => {
        result.push({
          key: index.toString(),
          ...item,
        })
      })
    }
    return result
  }

  private transformColumnType(type: string) {
    switch (type) {
      case 'varchar':
        return '字符串'
      case 'date':
        return '日期'
      case 'int':
        return '整数'
      case 'decimal':
        return '小数'
      case 'text':
        return '文本'
      default:
        return '不知名类型'
    }
  }

  public get isUploading() {
    return DataStore.isUploading
  }

  // 导入表格型数据时可以更改数据类型
  public get showSelect() {
    if (DataStore.isUploading && this.dataType === 'table') {
      return true
    }
    return false
  }

  public get showSemantic() {
    return this.showSelect || this.dataType === 'database'
  }

  private get displayMenuItem() {
    return this.menuItem
    // return this.menuItem.filter(item => item.value !== this.sourceType)
  }

  public get selectedImportType() {
    return DataStore.selectedImportType
  }

  @Emit('changeColType')
  public handleChange(colIndex: number, colType: string) {
    console.log('change col type:')
    console.log(colType)
    console.log(colIndex)
    return { index: colIndex, type: colType }
  }

  // 菜单点击事件
  public columnMenuClick(index: number, visible: boolean) {
    this.menuIsVisible[index] = !visible
  }
}
</script>

<style lang="less" scoped>
.ant-table-column-title {
  margin-right: 10px;
}

/deep/ .type-select {
  border-radius: 4px;
  color: #5d637e;
  width: 82px;
}

.col-type {
  color: #5d637e;
  font-weight: normal;
  margin-right: 8px;
}

// 表头
/deep/ .ant-table-header {
  .ant-table-row-cell-break-word {
    padding: 11px 16px;

    .ant-table-header-column {
      line-height: 24px;
    }
  }

  .ant-table-thead > tr > th {
    padding: 11px 16px;
  }
}

/deep/ .ant-table-tbody > tr > td {
  padding: 8px 16px;
}

/deep/ .ant-table-column-title {
  span:first-child {
    color: #373b52;
    font-weight: bold;
    margin-right: 8px;
  }
}

/deep/ .ant-table-fixed-right {
  height: calc(100% - 5px);

  .ant-table-header {
    height: 48px;

    .ant-table-row-cell-break-word {
      padding: 11px 16px;
    }
  }

  .ant-table-tbody {
    .ant-table-row-cell-break-word {
      padding: 8px 16px;
    }
  }
}

// 表数据行
/deep/ .ant-table-body {
  .ant-table-row-cell-break-word {
    padding: 8px 16px;
  }
}

.table-title {
  display: inline-block;
  max-width: 88px;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: bottom;
  white-space: nowrap;
}

.text-ellipsis {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: bottom;
  white-space: nowrap;
}

/deep/.ant-table-body,
/deep/.ant-table-body-inner {
  overflow-y: auto !important;

  &::-webkit-scrollbar {
    height: 6px;
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(144, 147, 153, 0.5);
    border-radius: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    border-radius: 5px;
  }
}

/deep/ .ant-dropdown-menu-item {
  .column-type-icon {
    color: #5d637e;
    font-size: 12px;
  }

  .anticon {
    margin-right: 4px;
  }
}

.ant-dropdown-menu-item > .anticon:first-child,
.ant-dropdown-menu-submenu-title > .anticon:first-child,
.ant-dropdown-menu-item > span > .anticon:first-child,
.ant-dropdown-menu-submenu-title > span > .anticon:first-child {
  margin-right: 4px;
}

.column-type-icon-trigger {
  color: #6973ff;
  display: inline-block;
  font-size: 11px;
  margin-left: 2px;
  width: 100%;
}

.column-type-icon-trigger:hover {
  cursor: pointer;
}

.arrow {
  color: #5b67e3;
  font-size: 10px;
  margin-left: 3px;

  &.menu-open {
    transform: rotate(180deg);
  }
}

/deep/ .ant-dropdown-menu-item-disabled,
.ant-dropdown-menu-submenu-title-disabled {
  color: #373b52;
  font-size: 14px;
  font-weight: 600;
  letter-spacing: 1px;
  line-height: 20px;
}
</style>
